﻿using fuzhu;
using SqlSuarEntity;
using SqlSugar;
using SqlSugar.Extensions;
using System.Data;
using System.Data.SqlClient;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.AS;
using XXX.Models.XXXEntities;
using ZDEntity;
using static XXX.Models.WDFT.WDFT_SaleOrderJinDu;

namespace Yonyou.U8.BO
{
    /// <summary>
    ///不能直接继承，因为后面还要转换
    /// </summary>
    public class InventoryVM
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public API_Inventory entity { get; set; }

        public InventoryVM()
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

        /// <summary>
        /// 导入U8，新增或修改
        /// </summary>
        /// <returns></returns>
        public  RetModel2 Import()
        {
               
            try
            {
                //检查是否存在这个编码
                bool binv = Exists(entity.cInvCode);
                if (!string.IsNullOrWhiteSpace(entity.cSTComUnitCode))
                {
                    entity.cSAComUnitCode = entity.cSTComUnitCode;
                    entity.cPUComUnitCode = entity.cSTComUnitCode;
                    entity.cCAComUnitCode = entity.cSTComUnitCode;
                    entity.cCAComUnitCode = entity.cSTComUnitCode;
                    entity.cShopUnit = entity.cSTComUnitCode;
                    entity.cProductUnit =   entity.cSTComUnitCode; 
                }
                if (!binv)
                {
                    return this.Add();
                }
                else
                {
                    return this.Update();
                }               
               
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }

        public void MergeEntity()
        {
            //取默认值合并
            entity = ASService.MergeEntity<API_Inventory>(entity, CanShu.invModel);
        }

        private static readonly object _inventoryLock = new object();

        /// <summary>
        /// 存货档案增加。 按model进行添加
        /// </summary>
        public RetModel2  ImportByModel()
        {
            lock (_inventoryLock) // 使用应用层锁
            {
                //dt包含  cinvcode，cinvname,参照产品编码
                SqlTransaction tran = DbHelper2.BeginTrans(conStr);
                try
                {
                    // 检查是否存在
                    string checkSql =$"SELECT COUNT(1) FROM Inventory WHERE cInvCode = '{entity.cInvCode}'";
                    int exists = DbHelper.GetDbInt( DbHelper2.GetSingleWithTrans(checkSql, tran));

                    if (exists > 0)
                    {
                        return DBService.ReOKObject("存货已存在");
                    }


                    //定义分类规则  存货分类+4位流水
                    string sQLString = @" delete from inventory_sub where cinvsubcode = @cinvcode
    delete from bas_part where invcode = @cinvcode  delete from inventory where cinvcode = @cinvcode";
                    DbHelper2.ExecuteSqlWithTrans(sQLString, new SqlParameter[]{
                       new SqlParameter("@cinvcode",entity.cInvCode)}, CommandType.Text, tran);


                    //获得partid
                    int ioldPartid = DbHelper.GetDbInt(DbHelper2.GetSingleWithTrans("select max(partid) from bas_part", tran));
                    // 获取当前最大 PartId
                    sQLString = @"SELECT CurrentMaxId FROM PartIdTracker WHERE TableName = 'bas_part'";
                    int currentMaxId = Convert.ToInt32(DbHelper2.GetSingleWithTrans(sQLString, tran));
                    if (ioldPartid > currentMaxId)
                    {
                        currentMaxId = ioldPartid;
                    }
                    // 更新 PartIdTracker 表中的最大 PartId
                    int iPartid = currentMaxId + 1;
                    sQLString = @"UPDATE PartIdTracker SET CurrentMaxId = @newPartId WHERE TableName = 'bas_part'";
                    DbHelper2.ExecuteSqlWithTrans(sQLString, new SqlParameter[] {
            new SqlParameter("@newPartId", iPartid)
        }, CommandType.Text, tran);

                    #region 插入bas_part
                    sQLString = @" INSERT INTO [bas_part]
           ([PartId]
           ,[InvCode]
           ,[Free1]
           ,[Free2]
           ,[Free3]
           ,[Free4]
           ,[Free5]
           ,[Free6]
           ,[Free7]
           ,[Free8]
           ,[Free9]
           ,[Free10]
           ,[SafeQty]
           ,[MinQty]
           ,[MulQty]
           ,[FixQty]
           ,[bVirtual]
           ,[DrawCode]
           ,[LLC]
           ,[cBasEngineerFigNo]
           ,[fBasMaxSupply]
           ,[iSurenessType]
           ,[iDateType]
           ,[iDateSum]
           ,[iDynamicSurenessType]
           ,[iBestrowSum]
           ,[iPercentumSum]
           ,[RoundingFactor]
           ,[FreeStockFlag])
  select  @partid
           ,@cinvcode
           ,[Free1]
           ,[Free2]
           ,[Free3]
           ,[Free4]
           ,[Free5]
           ,[Free6]
           ,[Free7]
           ,[Free8]
           ,[Free9]
           ,[Free10]
           ,[SafeQty]
           ,[MinQty]
           ,[MulQty]
           ,[FixQty]
           ,[bVirtual]
           ,[DrawCode]
           ,[LLC]
           ,[cBasEngineerFigNo]
           ,[fBasMaxSupply]
           ,[iSurenessType]
           ,[iDateType]
           ,[iDateSum]
           ,[iDynamicSurenessType]
           ,[iBestrowSum]
           ,[iPercentumSum]
           ,[RoundingFactor]
           ,[FreeStockFlag]  from bas_part where invcode = @Model
and not exists(select * from bas_part where invcode =@cinvcode)
";


                    DbHelper2.ExecuteSqlWithTrans(sQLString, new SqlParameter[]{
                       new SqlParameter("@cinvcode",entity.cInvCode),
                       new SqlParameter("@partid",iPartid),
                       new SqlParameter("@Model",entity.model),}, CommandType.Text, tran);
                    #endregion

                    #region 查询存货辅助表
                    sQLString = @"INSERT INTO [Inventory_Sub]
           ([cInvSubCode]
           ,[fBuyExcess]
           ,[iSurenessType]
           ,[iDateType]
           ,[iDateSum]
           ,[iDynamicSurenessType]
           ,[iBestrowSum]
           ,[iPercentumSum]
           ,[bIsAttachFile]
           ,[bInByProCheck]
           ,[iRequireTrackStyle]
           ,[iExpiratDateCalcu]
           ,[iBOMExpandUnitType]
           ,[bPurPriceFree1]
           ,[bPurPriceFree2]
           ,[bPurPriceFree3]
           ,[bPurPriceFree4]
           ,[bPurPriceFree5]
           ,[bPurPriceFree6]
           ,[bPurPriceFree7]
           ,[bPurPriceFree8]
           ,[bPurPriceFree9]
           ,[bPurPriceFree10]
           ,[bOMPriceFree1]
           ,[bOMPriceFree2]
           ,[bOMPriceFree3]
           ,[bOMPriceFree4]
           ,[bOMPriceFree5]
           ,[bOMPriceFree6]
           ,[bOMPriceFree7]
           ,[bOMPriceFree8]
           ,[bOMPriceFree9]
           ,[bOMPriceFree10]
           ,[bSalePriceFree1]
           ,[bSalePriceFree2]
           ,[bSalePriceFree3]
           ,[bSalePriceFree4]
           ,[bSalePriceFree5]
           ,[bSalePriceFree6]
           ,[bSalePriceFree7]
           ,[bSalePriceFree8]
           ,[bSalePriceFree9]
           ,[bSalePriceFree10]
           ,[fInvOutUpLimit]
           ,[bBondedInv]
           ,[bBatchCreate]
           ,[bBatchProperty1]
           ,[bBatchProperty2]
           ,[bBatchProperty3]
           ,[bBatchProperty4]
           ,[bBatchProperty5]
           ,[bBatchProperty6]
           ,[bBatchProperty7]
           ,[bBatchProperty8]
           ,[bBatchProperty9]
           ,[bBatchProperty10]
           ,[bControlFreeRange1]
           ,[bControlFreeRange2]
           ,[bControlFreeRange3]
           ,[bControlFreeRange4]
           ,[bControlFreeRange5]
           ,[bControlFreeRange6]
           ,[bControlFreeRange7]
           ,[bControlFreeRange8]
           ,[bControlFreeRange9]
           ,[bControlFreeRange10]
           ,[fInvCIQExch]
           ,[iWarrantyPeriod]
           ,[iWarrantyUnit]
           ,[bInvKeyPart]
           ,[iAcceptEarlyDays]
           ,[fProcessCost]
           ,[fCurLLaborCost]
           ,[fCurLVarManuCost]
           ,[fCurLFixManuCost]
           ,[fCurLOMCost]
           ,[fNextLLaborCost]
           ,[fNextLVarManuCost]
           ,[fNextLFixManuCost]
           ,[fNextLOMCost]
           ,[dInvCreateDatetime]
           ,[cInvAppDocNo]
           ,[bPUQuota]
           ,[bInvROHS]
           ,[bPrjMat]
           ,[fPrjMatLimit]
           ,[bInvAsset]
           ,[bSrvProduct]
           ,[iAcceptDelayDays]
           ,[iPlanCheckDay]
           ,[iMaterialsCycle]
           ,[iDrawType]
           ,[bSCkeyProjections]
           ,[iSupplyPeriodType]
           ,[iTimeBucketId]
           ,[iAvailabilityDate]
           ,[fMaterialCost]
           ,[bImport]
           ,[iNearRejectDays]
           ,[bCheckSubitemCost]
           ,[fRoundFactor]
           ,[bConsiderFreeStock]
           ,[bSuitRetail])
    select @cinvcode
           ,[fBuyExcess]
           ,[iSurenessType]
           ,[iDateType]
           ,[iDateSum]
           ,[iDynamicSurenessType]
           ,[iBestrowSum]
           ,[iPercentumSum]
           ,[bIsAttachFile]
           ,[bInByProCheck]
           ,[iRequireTrackStyle]
           ,[iExpiratDateCalcu]
           ,[iBOMExpandUnitType]
           ,[bPurPriceFree1]
           ,[bPurPriceFree2]
           ,[bPurPriceFree3]
           ,[bPurPriceFree4]
           ,[bPurPriceFree5]
           ,[bPurPriceFree6]
           ,[bPurPriceFree7]
           ,[bPurPriceFree8]
           ,[bPurPriceFree9]
           ,[bPurPriceFree10]
           ,[bOMPriceFree1]
           ,[bOMPriceFree2]
           ,[bOMPriceFree3]
           ,[bOMPriceFree4]
           ,[bOMPriceFree5]
           ,[bOMPriceFree6]
           ,[bOMPriceFree7]
           ,[bOMPriceFree8]
           ,[bOMPriceFree9]
           ,[bOMPriceFree10]
           ,[bSalePriceFree1]
           ,[bSalePriceFree2]
           ,[bSalePriceFree3]
           ,[bSalePriceFree4]
           ,[bSalePriceFree5]
           ,[bSalePriceFree6]
           ,[bSalePriceFree7]
           ,[bSalePriceFree8]
           ,[bSalePriceFree9]
           ,[bSalePriceFree10]
           ,[fInvOutUpLimit]
           ,[bBondedInv]
           ,[bBatchCreate]
           ,[bBatchProperty1]
           ,[bBatchProperty2]
           ,[bBatchProperty3]
           ,[bBatchProperty4]
           ,[bBatchProperty5]
           ,[bBatchProperty6]
           ,[bBatchProperty7]
           ,[bBatchProperty8]
           ,[bBatchProperty9]
           ,[bBatchProperty10]
           ,[bControlFreeRange1]
           ,[bControlFreeRange2]
           ,[bControlFreeRange3]
           ,[bControlFreeRange4]
           ,[bControlFreeRange5]
           ,[bControlFreeRange6]
           ,[bControlFreeRange7]
           ,[bControlFreeRange8]
           ,[bControlFreeRange9]
           ,[bControlFreeRange10]
           ,[fInvCIQExch]
           ,[iWarrantyPeriod]
           ,[iWarrantyUnit]
           ,[bInvKeyPart]
           ,[iAcceptEarlyDays]
           ,[fProcessCost]
           ,[fCurLLaborCost]
           ,[fCurLVarManuCost]
           ,[fCurLFixManuCost]
           ,[fCurLOMCost]
           ,[fNextLLaborCost]
           ,[fNextLVarManuCost]
           ,[fNextLFixManuCost]
           ,[fNextLOMCost]
           ,[dInvCreateDatetime]
           ,[cInvAppDocNo]
           ,[bPUQuota]
           ,[bInvROHS]
           ,[bPrjMat]
           ,[fPrjMatLimit]
           ,[bInvAsset]
           ,[bSrvProduct]
           ,[iAcceptDelayDays]
           ,[iPlanCheckDay]
           ,[iMaterialsCycle]
           ,[iDrawType]
           ,[bSCkeyProjections]
           ,[iSupplyPeriodType]
           ,[iTimeBucketId]
           ,[iAvailabilityDate]
           ,[fMaterialCost]
           ,[bImport]
           ,[iNearRejectDays]
           ,[bCheckSubitemCost]
           ,[fRoundFactor]
           ,[bConsiderFreeStock]
           ,[bSuitRetail] from  [Inventory_Sub] where cInvSubCode = @Model
and not  exists(select * from Inventory_Sub where cInvSubCode =@cinvcode)";
                    DbHelper2.ExecuteSqlWithTrans(sQLString, new SqlParameter[]{
                       new SqlParameter("@cinvcode",entity.cInvCode),
                       new SqlParameter("@Model",entity.model)}, CommandType.Text, tran);
                    #endregion



                    #region 查询存货档案
                    sQLString = @"INSERT INTO [Inventory]
           ([cInvCode]
           ,[cInvAddCode]
           ,[cInvName]
           ,[cInvStd]
           ,[cInvCCode]
           ,[cVenCode]
           ,[cReplaceItem]
           ,[cPosition]
           ,[bSale]
           ,[bPurchase]
           ,[bSelf]
           ,[bComsume]
           ,[bProducing]
           ,[bService]
           ,[bAccessary]
           ,[iTaxRate]
           ,[iInvWeight]
           ,[iVolume]
           ,[iInvRCost]
           ,[iInvSPrice]
           ,[iInvSCost]
           ,[iInvLSCost]
           ,[iInvNCost]
           ,[iInvAdvance]
           ,[iInvBatch]
           ,[iSafeNum]
           ,[iTopSum]
           ,[iLowSum]
           ,[iOverStock]
           ,[cInvABC]
           ,[bInvQuality]
           ,[bInvBatch]
           ,[bInvEntrust]
           ,[bInvOverStock]
           ,[dSDate]
           ,[dEDate]
           ,[bFree1]
           ,[bFree2]
           ,[cInvDefine1]
           ,[cInvDefine2]
           ,[cInvDefine3]
           ,[bInvType]
           ,[iInvMPCost]
           ,[cQuality]
           ,[iInvSaleCost]
           ,[iInvSCost1]
           ,[iInvSCost2]
           ,[iInvSCost3]
           ,[bFree3]
           ,[bFree4]
           ,[bFree5]
           ,[bFree6]
           ,[bFree7]
           ,[bFree8]
           ,[bFree9]
           ,[bFree10]
           ,[cCreatePerson]
           ,[cModifyPerson]
           ,[dModifyDate]
           ,[fSubscribePoint]
           ,[fVagQuantity]
           ,[cValueType]
           ,[bFixExch]
           ,[fOutExcess]
           ,[fInExcess]
           ,[iMassDate]
           ,[iWarnDays]
           ,[fExpensesExch]
           ,[bTrack]
           ,[bSerial]
           ,[bBarCode]
           ,[iId]
           ,[cBarCode]
           ,[cInvDefine4]
           ,[cInvDefine5]
           ,[cInvDefine6]
           ,[cInvDefine7]
           ,[cInvDefine8]
           ,[cInvDefine9]
           ,[cInvDefine10]
           ,[cInvDefine11]
           ,[cInvDefine12]
           ,[cInvDefine13]
           ,[cInvDefine14]
           ,[cInvDefine15]
           ,[cInvDefine16]
           ,[iGroupType]
           ,[cGroupCode]
           ,[cComUnitCode]
           ,[cAssComUnitCode]
           ,[cSAComUnitCode]
           ,[cPUComUnitCode]
           ,[cSTComUnitCode]
           ,[cCAComUnitCode]
           ,[cFrequency]
           ,[iFrequency]
           ,[iDays]
           ,[dLastDate]
           ,[iWastage]
           ,[bSolitude]
           ,[cEnterprise]
           ,[cAddress]
           ,[cFile]
           ,[cLabel]
           ,[cCheckOut]
           ,[cLicence]
           ,[bSpecialties]
           ,[cDefWareHouse]
           ,[iHighPrice]
           ,[iExpSaleRate]
           ,[cPriceGroup]
           ,[cOfferGrade]
           ,[iOfferRate]
           ,[cMonth]
           ,[iAdvanceDate]
           ,[cCurrencyName]
           ,[cProduceAddress]
           ,[cProduceNation]
           ,[cRegisterNo]
           ,[cEnterNo]
           ,[cPackingType]
           ,[cEnglishName]
           ,[bPropertyCheck]
           ,[cPreparationType]
           ,[cCommodity]
           ,[iRecipeBatch]
           ,[cNotPatentName]
           ,[bPromotSales]
           ,[iPlanPolicy]
           ,[iROPMethod]
           ,[iBatchRule]
           ,[fBatchIncrement]
           ,[iAssureProvideDays]
           ,[iTestStyle]
           ,[iDTMethod]
           ,[fDTRate]
           ,[fDTNum]
           ,[cDTUnit]
           ,[iDTStyle]
           ,[iQTMethod]
           ,[PictureGUID]
           ,[bPlanInv]
           ,[bProxyForeign]
           ,[bATOModel]
           ,[bCheckItem]
           ,[bPTOModel]
           ,[bEquipment]
           ,[cProductUnit]
           ,[fOrderUpLimit]
           ,[cMassUnit]
           ,[fRetailPrice]
           ,[cInvDepCode]
           ,[iAlterAdvance]
           ,[fAlterBaseNum]
           ,[cPlanMethod]
           ,[bMPS]
           ,[bROP]
           ,[bRePlan]
           ,[cSRPolicy]
           ,[bBillUnite]
           ,[iSupplyDay]
           ,[fSupplyMulti]
           ,[fMinSupply]
           ,[bCutMantissa]
           ,[cInvPersonCode]
           ,[iInvTfId]
           ,[cEngineerFigNo]
           ,[bInTotalCost]
           ,[iSupplyType]
           ,[bConfigFree1]
           ,[bConfigFree2]
           ,[bConfigFree3]
           ,[bConfigFree4]
           ,[bConfigFree5]
           ,[bConfigFree6]
           ,[bConfigFree7]
           ,[bConfigFree8]
           ,[bConfigFree9]
           ,[bConfigFree10]
           ,[iDTLevel]
           ,[cDTAQL]
           ,[bPeriodDT]
           ,[cDTPeriod]
           ,[iBigMonth]
           ,[iBigDay]
           ,[iSmallMonth]
           ,[iSmallDay]
           ,[bOutInvDT]
           ,[bBackInvDT]
           ,[iEndDTStyle]
           ,[bDTWarnInv]
           ,[fBackTaxRate]
           ,[cCIQCode]
           ,[cWGroupCode]
           ,[cWUnit]
           ,[fGrossW]
           ,[cVGroupCode]
           ,[cVUnit]
           ,[fLength]
           ,[fWidth]
           ,[fHeight]
           ,[iDTUCounter]
           ,[iDTDCounter]
           ,[iBatchCounter]
           ,[cShopUnit]
           ,[cPurPersonCode]
           ,[bImportMedicine]
           ,[bFirstBusiMedicine]
           ,[bForeExpland]
           ,[cInvPlanCode]
           ,[fConvertRate]
           ,[dReplaceDate]
           ,[bInvModel]
           ,[bKCCutMantissa]
           ,[bReceiptByDT]
           ,[iImpTaxRate]
           ,[iExpTaxRate]
           ,[bExpSale]
           ,[iDrawBatch]
           ,[bCheckBSATP]
           ,[cInvProjectCode]
           ,[iTestRule]
           ,[cRuleCode]
           ,[bCheckFree1]
           ,[bCheckFree2]
           ,[bCheckFree3]
           ,[bCheckFree4]
           ,[bCheckFree5]
           ,[bCheckFree6]
           ,[bCheckFree7]
           ,[bCheckFree8]
           ,[bCheckFree9]
           ,[bCheckFree10]
           ,[bBomMain]
           ,[bBomSub]
           ,[bProductBill]
           ,[iCheckATP]
           ,[iInvATPId]
           ,[iPlanTfDay]
           ,[iOverlapDay]
           ,[bPiece]
           ,[bSrvItem]
           ,[bSrvFittings]
           ,[fMaxSupply]
           ,[fMinSplit]
           ,[bSpecialOrder]
           ,[bTrackSaleBill]
           ,[cInvMnemCode]
           ,[iPlanDefault]
           ,[iPFBatchQty]
           ,[iAllocatePrintDgt]
           ,[bCheckBatch]
           ,[bMngOldpart]
           ,[iOldpartMngRule])
    select @cinvcode
           ,@cinvaddcode
           ,@cinvname
           ,(CASE WHEN ISNULL(@cinvstd,'') = '' THEN [cInvStd] ELSE @cinvstd END)
           ,(CASE WHEN ISNULL(@cinvccode,'') = '' THEN [cInvCCode] ELSE @cinvccode END)
           ,[cVenCode]
           ,[cReplaceItem]
           ,[cPosition]
           ,[bSale]
           ,[bPurchase]
           ,[bSelf]
           ,[bComsume]
           ,[bProducing]
           ,[bService]
           ,[bAccessary]
           ,[iTaxRate]
           ,[iInvWeight]
           ,[iVolume]
           ,[iInvRCost]
           ,[iInvSPrice]
           ,[iInvSCost]
           ,[iInvLSCost]
           ,[iInvNCost]
           ,[iInvAdvance]
           ,[iInvBatch]
           ,[iSafeNum]
           ,[iTopSum]
           ,[iLowSum]
           ,[iOverStock]
           ,[cInvABC]
           ,[bInvQuality]
           ,[bInvBatch]
           ,[bInvEntrust]
           ,[bInvOverStock]
           ,[dSDate]
           ,[dEDate]
           ,[bFree1]
           ,[bFree2]
           ,[cInvDefine1]
           ,[cInvDefine2]
           ,[cInvDefine3]
           ,[bInvType]
           ,[iInvMPCost]
           ,[cQuality]
           ,[iInvSaleCost]
           ,[iInvSCost1]
           ,[iInvSCost2]
           ,[iInvSCost3]
           ,[bFree3]
           ,[bFree4]
           ,[bFree5]
           ,[bFree6]
           ,[bFree7]
           ,[bFree8]
           ,[bFree9]
           ,[bFree10]
           ,[cCreatePerson]
           ,[cModifyPerson]
           ,[dModifyDate]
           ,[fSubscribePoint]
           ,[fVagQuantity]
           ,[cValueType]
           ,[bFixExch]
           ,[fOutExcess]
           ,[fInExcess]
           ,[iMassDate]
           ,[iWarnDays]
           ,[fExpensesExch]
           ,[bTrack]
           ,[bSerial]
           ,[bBarCode]
           ,[iId]
           ,[cBarCode]
           ,[cInvDefine4]
           ,[cInvDefine5]
           ,[cInvDefine6]
           ,[cInvDefine7]
           ,[cInvDefine8]
           ,[cInvDefine9]
           ,[cInvDefine10]
           ,[cInvDefine11]
           ,[cInvDefine12]
           ,[cInvDefine13]
           ,[cInvDefine14]
           ,[cInvDefine15]
           ,[cInvDefine16]
           ,[iGroupType]
           ,(CASE WHEN ISNULL(@cGroupCode,'') = '' THEN [cGroupCode] ELSE @cGroupCode END)
           ,(CASE WHEN ISNULL(@cComUnitCode,'') = '' THEN [cComUnitCode] ELSE @cComUnitCode END)
           ,[cAssComUnitCode]
           ,[cSAComUnitCode]
           ,[cPUComUnitCode]
           ,[cSTComUnitCode]
           ,[cCAComUnitCode]
           ,[cFrequency]
           ,[iFrequency]
           ,[iDays]
           ,[dLastDate]
           ,[iWastage]
           ,[bSolitude]
           ,[cEnterprise]
           ,[cAddress]
           ,[cFile]
           ,[cLabel]
           ,[cCheckOut]
           ,[cLicence]
           ,[bSpecialties]
           ,[cDefWareHouse]
           ,[iHighPrice]
           ,[iExpSaleRate]
           ,[cPriceGroup]
           ,[cOfferGrade]
           ,[iOfferRate]
           ,[cMonth]
           ,[iAdvanceDate]
           ,[cCurrencyName]
           ,[cProduceAddress]
           ,[cProduceNation]
           ,[cRegisterNo]
           ,[cEnterNo]
           ,[cPackingType]
           ,[cEnglishName]
           ,[bPropertyCheck]
           ,[cPreparationType]
           ,[cCommodity]
           ,[iRecipeBatch]
           ,[cNotPatentName]
           ,[bPromotSales]
           ,[iPlanPolicy]
           ,[iROPMethod]
           ,[iBatchRule]
           ,[fBatchIncrement]
           ,[iAssureProvideDays]
           ,[iTestStyle]
           ,[iDTMethod]
           ,[fDTRate]
           ,[fDTNum]
           ,[cDTUnit]
           ,[iDTStyle]
           ,[iQTMethod]
           ,[PictureGUID]
           ,[bPlanInv]
           ,[bProxyForeign]
           ,[bATOModel]
           ,[bCheckItem]
           ,[bPTOModel]
           ,[bEquipment]
           ,[cProductUnit]
           ,[fOrderUpLimit]
           ,[cMassUnit]
           ,[fRetailPrice]
           ,[cInvDepCode]
           ,[iAlterAdvance]
           ,[fAlterBaseNum]
           ,[cPlanMethod]
           ,[bMPS]
           ,[bROP]
           ,[bRePlan]
           ,[cSRPolicy]
           ,[bBillUnite]
           ,[iSupplyDay]
           ,[fSupplyMulti]
           ,[fMinSupply]
           ,[bCutMantissa]
           ,[cInvPersonCode]
           ,[iInvTfId]
           ,[cEngineerFigNo]
           ,[bInTotalCost]
           ,[iSupplyType]
           ,[bConfigFree1]
           ,[bConfigFree2]
           ,[bConfigFree3]
           ,[bConfigFree4]
           ,[bConfigFree5]
           ,[bConfigFree6]
           ,[bConfigFree7]
           ,[bConfigFree8]
           ,[bConfigFree9]
           ,[bConfigFree10]
           ,[iDTLevel]
           ,[cDTAQL]
           ,[bPeriodDT]
           ,[cDTPeriod]
           ,[iBigMonth]
           ,[iBigDay]
           ,[iSmallMonth]
           ,[iSmallDay]
           ,[bOutInvDT]
           ,[bBackInvDT]
           ,[iEndDTStyle]
           ,[bDTWarnInv]
           ,[fBackTaxRate]
           ,[cCIQCode]
           ,[cWGroupCode]
           ,[cWUnit]
           ,[fGrossW]
           ,[cVGroupCode]
           ,[cVUnit]
           ,[fLength]
           ,[fWidth]
           ,[fHeight]
           ,[iDTUCounter]
           ,[iDTDCounter]
           ,[iBatchCounter]
           ,[cShopUnit]
           ,[cPurPersonCode]
           ,[bImportMedicine]
           ,[bFirstBusiMedicine]
           ,[bForeExpland]
           ,[cInvPlanCode]
           ,[fConvertRate]
           ,[dReplaceDate]
           ,[bInvModel]
           ,[bKCCutMantissa]
           ,[bReceiptByDT]
           ,[iImpTaxRate]
           ,[iExpTaxRate]
           ,[bExpSale]
           ,[iDrawBatch]
           ,[bCheckBSATP]
           ,[cInvProjectCode]
           ,[iTestRule]
           ,[cRuleCode]
           ,[bCheckFree1]
           ,[bCheckFree2]
           ,[bCheckFree3]
           ,[bCheckFree4]
           ,[bCheckFree5]
           ,[bCheckFree6]
           ,[bCheckFree7]
           ,[bCheckFree8]
           ,[bCheckFree9]
           ,[bCheckFree10]
           ,[bBomMain]
           ,[bBomSub]
           ,[bProductBill]
           ,[iCheckATP]
           ,[iInvATPId]
           ,[iPlanTfDay]
           ,[iOverlapDay]
           ,[bPiece]
           ,[bSrvItem]
           ,[bSrvFittings]
           ,[fMaxSupply]
           ,[fMinSplit]
           ,[bSpecialOrder]
           ,[bTrackSaleBill]
           ,[cInvMnemCode]
           ,[iPlanDefault]
           ,[iPFBatchQty]
           ,[iAllocatePrintDgt]
           ,[bCheckBatch]
           ,[bMngOldpart]
           ,[iOldpartMngRule] from inventory where cInvCode = @Model
and not  exists(select * from inventory where cInvCode =@cinvcode) ";

                    DbHelper2.ExecuteSqlWithTrans(sQLString, new SqlParameter[]{
                       new SqlParameter("@cinvcode",entity.cInvCode),
                       new SqlParameter("@cinvname", entity.cInvName),
                       new SqlParameter("@cinvaddcode",entity.cInvCode),
                       new SqlParameter("@cinvccode",DbHelper.ToDbValue(entity.cInvCCode)),
                       new SqlParameter("@cinvstd",DbHelper.ToDbValue(entity.cInvStd)),
                       //new SqlParameter("@cinvdefine1",DbHelper.ToDbValue(dr["9"])),
                       //new SqlParameter("@cinvdefine2",DbHelper.ToDbValue(dr["25"])),
                       //new SqlParameter("@cinvdefine3",DbHelper.ToDbValue(dr["18"])),
                       //new SqlParameter("@cinvdefine4",DbHelper.ToDbValue(dr["26"])),
                       //new SqlParameter("@cinvdefine5",DbHelper.ToDbValue(dr["27"])),
                       //new SqlParameter("@cinvdefine6",DbHelper.ToDbValue(dr["19"])),
                       //new SqlParameter("@cinvdefine7",DbHelper.ToDbValue(dr["20"])),
                       //new SqlParameter("@cinvdefine8",DbHelper.ToDbValue(dr["21"])),
                       //new SqlParameter("@cinvdefine9",DbHelper.ToDbValue(dr["22"])),
                       //new SqlParameter("@cinvdefine10",DbHelper.ToDbValue(dr["23"])),
                       //new SqlParameter("@cinvdefine13",DbHelper.ToDbValue(dr["28"])),
                       new SqlParameter("@cGroupCode",DbHelper.ToDbValue(entity.cGroupCode)),
                       new SqlParameter("@cComUnitCode",DbHelper.ToDbValue(entity.cComUnitCode)),
                       new SqlParameter("@Model",entity.model)}, CommandType.Text, tran);
                    #endregion

                    #region 插入扩展自定义项
                    //sQLString = @"insert into Inventory_extradefine(cinvcode,cidefine1)
                    //        values(@cinvcode,@cidefine1)";
                    //DbHelper2.ExecuteSqlWithTrans(sQLString, new SqlParameter[]{
                    //       new SqlParameter("@cinvcode",cInvcode),
                    //       new SqlParameter("@cidefine1",dr["11"])}, CommandType.Text, tran);
                    #endregion

                    //是否消耗= 1
                    //                    if (model.ATO == "1")
                    //                    {
                    sQLString = @"UPDATE inventory SET bComsume=1 FROM  inventory
WHERE cInvCode =@cinvcode ";
                    DbHelper2.ExecuteSqlWithTrans(sQLString, new SqlParameter[]{
                       new SqlParameter("@cinvcode",entity.cInvCode)}, CommandType.Text, tran);
                    //                    }


                    DbHelper2.CommitTransAndCloseConnection(tran);



                    //                //判断存货档案是否是多计量组
                    //                sQLString = string.Format(@"UPDATE  a SET igrouptype  =b.iGroupType FROM inventory a,ComputationGroup b WHERE a.cGroupCode   = b.cGroupCode
                    //AND a.iGroupType<>b.iGroupType and a.cinvcode = '{0}'", cInvcode);
                    //                DbHelper.ExecuteNonQuery(sQLString);


                    return DBService.ReOKObject("新增完成");

                }
                catch (Exception exception)
                {
                    DbHelper2.RollbackAndCloseConnection(tran);
                    return DBService.ReErrObject("新增失败" + exception.Message);
                }
            }
                
            

        }

        public RetModel2 Add()
        {
            try
            {
                string cerr;
                string cid;
                 
                if (InventoryDALCO.AddInventory(entity, xmlConfig, out cerr, out cid))
                {
                    return DBService.ReOKObject("新增完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        ///  变更
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2  Update()
        {
            try
            {
                string cerr;
                string cid; 
                if (InventoryDALCO.ModifyInventory(entity, xmlConfig, out cerr))
                {
                    return DBService.ReOKObject("修改完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
             
        }

        public RetModel2 Delete()
        {
            try
            {
                string cerr;
                string cid;

                if (InventoryDALCO.DelInventory(entity.cInvCode, xmlConfig, out cerr))
                {
                    return DBService.ReOKObject("删除完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
        /// <summary>
        /// 检查部门是否存在，返回U8部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Inventory GetByInvcode(string cInvCode)
        {
            if (string.IsNullOrEmpty(cInvCode))
            {
                return null;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            { 
                
                Inventory inv = db.Queryable<Inventory>().Where(x => x.cInvCode == cInvCode).First();
                 return inv; 
            } 
        
        }
        /// <summary>
        /// 检查存货编码是否存在
        /// </summary>
        /// <param name="cDepCode"></param>
        /// <returns></returns>
        public bool Exists(string cInvCode)
        {
           
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString =  conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

               bool bExists = db.Queryable<Inventory>().Where(x => x.cInvCode == cInvCode).Any();
               
               return bExists;
            }
        }

        /// <summary>
        /// 获得存货编码对应的partid,无结构自由项
        /// </summary>
        /// <returns></returns>
        public RetModel2 GetPartidNoFree(String cInvCode)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {

                   bas_part bas= db.Queryable<bas_part>().Where(x => x.InvCode == cInvCode).First();
                   if (bas==null)
                    {
                        return DBService.ReErrObject("没有此料号");
                    }
                   else
                    {
                        return DBService.ReOKObject(bas.PartId);
                    }

                   
                }

              
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }

        }


      

        /// <summary>
        /// 获得存货编码的辅助计量单位
        /// </summary>
        /// <returns></returns>
        public InvAuxCom GetAuxEntity(String cInvCode)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    string sql = string.Format(@"select a.cInvCode,a.iGroupType, a.cComUnitCode,cSTComUnitCode,convert(varchar(20), b.iChangRate) as iChangRate from inventory a
left join ComputationUnit b on a.cSTComUnitCode= b.cComunitCode and a.cGroupCode = b.cGroupCode
 where cinvcode='{0}' and a.iGroupType<>0 ", cInvCode);

                    InvAuxCom invAuxCom = db.SqlQueryable<InvAuxCom>(sql).First();
                    return invAuxCom;
                }
            }
            catch (Exception ex)
            {
                return null;
            }

        }

        /// <summary>
        /// 读取存货的常规属性，用于生单的转换
        /// </summary>
        /// <param name="cInvCode"></param>
        /// <returns></returns>
        public InvProperty GetInvProperty(String cInvCode,string dMDate, string dVDate)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                   
                    InvProperty invProperty = db.Queryable<Inventory>()
                                          .InnerJoin<Inventory_Sub>((a, b) => a.cInvCode == b.cInvSubCode)
                                          .LeftJoin<ComputationUnit>((a,b,c)=>a.cSTComUnitCode==c.cComunitCode && a.cGroupCode==c.cGroupCode)
                                          .Where((a, b,c) => a.cInvCode == cInvCode)
                                          .Select((a, b,c) => new InvProperty { 
                                          cInvCode=a.cInvCode,
                                          cGroupCode = a.cGroupCode,
                                          iGroupType = Convert.ToString(a.iGroupType),
                                          cSTComUnitCode=a.cSTComUnitCode,
                                          iChangRate= Convert.ToString(c.iChangRate),
                                          bInvBatch=a.bInvBatch,
                                          bInvQuality=a.bInvQuality,
                                          cMassUnit=a.cMassUnit,
                                          iMassDate=a.iMassDate,
                                          iexpiratdatecalcu =b.iExpiratDateCalcu,     
                                          }).First();


                    //有批次管理
                    if (invProperty!=null && invProperty.bInvQuality && !string.IsNullOrEmpty(DbHelper.GetDbString(dMDate)) )
                    {
                        //如果失效日期是空的，进行推算。如果不是空的，直接引用
                        if (string.IsNullOrEmpty(dVDate))
                        {
                            if (invProperty.cMassUnit == 1)
                            {
                                invProperty.dVDate = DbHelper.GetDbDate(dMDate).AddYears(DbHelper.GetDbInt(invProperty.iMassDate));
                            }
                            else if (invProperty.cMassUnit == 2)
                            {
                                invProperty.dVDate = DbHelper.GetDbDate(dMDate).AddMonths(DbHelper.GetDbInt(invProperty.iMassDate));
                            }
                            else if (invProperty.cMassUnit == 3)
                            {
                                invProperty.dVDate = DbHelper.GetDbDate(dMDate).AddDays(DbHelper.GetDbInt(invProperty.iMassDate));
                            }
                        }
                        else
                        {
                            invProperty.dVDate = DbHelper.GetDbDate(dVDate);
                            //if (string.IsNullOrEmpty(DbHelper.GetDbString(invProperty.cMassUnit)) )
                            //{
                            //    //cMassUnit，imassdate，什么都没填写，用失效日期
                               
                            //}
                        }
                        

                        //计算失效日期，
                        if (invProperty.iexpiratdatecalcu == 1 && !string.IsNullOrEmpty(DbHelper.GetDbString(invProperty.dVDate)))
                        { 
                            invProperty.dExpeireDate = DbHelper.GetDbDate(invProperty.dVDate).AddMonths(-1);
                        }
                        else if (invProperty.iexpiratdatecalcu==2 && !string.IsNullOrEmpty(DbHelper.GetDbString(invProperty.dVDate)))
                         {
                            invProperty.dExpeireDate = DbHelper.GetDbDate(invProperty.dVDate).AddDays(-1);
                        }
                        
                    }

                    return invProperty;
                }
            }
            catch (Exception ex)
            {
              throw ex;
            }

        }


        public void HandlerTopQty(SqlSugarClient db, HashSet<string> uniqueCinvCodes)
        {
            // Step 2: 针对每个唯一 cinvcode 进行处理
            foreach (string cinvcode in uniqueCinvCodes)
            {
                // 查询 inventory 实体
                var inventory = db.Queryable<Inventory>()
                                  .First(i => i.cInvCode == cinvcode);

                if (inventory != null)
                {
                    // Step 3: 如果 iTopSum / iLowSum 不为空，则更新 fHeight / fWidth
                    if (!string.IsNullOrEmpty(DbHelper.GetDbString(inventory.iTopSum)))
                    {
                        inventory.fHeight = inventory.iTopSum;
                    }

                    if (!string.IsNullOrEmpty(DbHelper.GetDbString(inventory.iLowSum)))
                    {
                        inventory.fWidth = inventory.iLowSum;
                    }

                    // Step 4: 清空 iTopSum 和 iLowSum
                    inventory.iTopSum = null;
                    inventory.iLowSum = null;

                    // Step 5: 更新数据库
                    db.Updateable(inventory).UpdateColumns(
                        it => new object[]
                        {
                it.fHeight,   // 更新 fHeight
                it.fWidth,    // 更新 fWidth
                it.iTopSum,   // 清空 iTopSum
                it.iLowSum    // 清空 iLowSum
                        }
                    ).Where(it => it.cInvCode == cinvcode).ExecuteCommand();
                }
            }
        }


        public void UnHandlerTopQty(SqlSugarClient db, HashSet<string> uniqueCinvCodes)
        {
            // Step 2: 针对每个唯一 cinvcode 进行处理
            foreach (string cinvcode in uniqueCinvCodes)
            {
                // 查询 inventory 实体
                var inventory = db.Queryable<Inventory>()
                                  .First(i => i.cInvCode == cinvcode);

                if (inventory != null)
                {
                    // Step 3: 如果 fHeight / fWidth 不为空，则更新 iTopSum / iLowSum
                    if (!string.IsNullOrEmpty(DbHelper.GetDbString(inventory.fHeight)))
                    {
                        inventory.iTopSum = inventory.fHeight;
                    }

                    if (!string.IsNullOrEmpty(DbHelper.GetDbString(inventory.fWidth)))
                    {
                        inventory.iLowSum = inventory.fWidth;
                    }

                    // Step 4: 清空 fHeight 和 fWidth
                    inventory.fHeight = null;
                    inventory.fWidth = null;

                    // Step 5: 更新数据库
                    db.Updateable(inventory).UpdateColumns(
                        it => new object[]
                        {
                it.fHeight,   // 更新 fHeight
                it.fWidth,    // 更新 fWidth
                it.iTopSum,   // 清空 iTopSum
                it.iLowSum    // 清空 iLowSum
                        }
                    ).Where(it => it.cInvCode == cinvcode).ExecuteCommand();
                }
            }
        }
    }
}
